package com.dd.cloud.common.config.common;


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * springboot容器启动后自动加载, 使用其getBean方法即可获取注入的bean
 * 可在无法被springboot管理的类上使用,获取springboot管理的bean
 * 使用方法 例:sharePresService = (SharePresServiceImpl) SpringContextJobUtil.getBean("sharePresServiceImpl");
 */
@Component
public class SpringContextJobUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    @SuppressWarnings("static-access")
    public void setApplicationContext(ApplicationContext contex)
            throws BeansException {
        context = contex;
    }

    /**
     * 通过name获取bean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    /**
     * 通过class获取Bean.
     */
    public static <T> T getBean(Class<T> clazz) {
        try {
            return context.getBean(clazz);
        } catch (BeansException e) {
            return null;
        }
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        if (!context.containsBean(name)) {
            return null;
        }
        return context.getBean(name, clazz);
    }

    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }


}
